package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Database.*;
import DataStorageClasses.*;
import ExceptionClasses.CantAccessEmailException;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import Utilities.*;
import Utilities.EmailClient.EmailHeader;
import Utilities.EmailClient.EmailInbox;

import com.mysql.*;

/**
 * Servlet implementation class addBusinessServlet
 */
@WebServlet("/EmailHeaderServlet")
public class EmailHeaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String business = (String) request.getSession().getAttribute("username");
		
		int start = Integer.valueOf(request.getParameter("start"));
		int number = Integer.valueOf(request.getParameter("number"));
		String sender = request.getParameter("sender");
		
		try {
			EmailClient client = new EmailClient(business);
			EmailInbox inbox;
			
			if (sender == null) {
				inbox = client.getInbox(number, start);
			}
			else {
				inbox = client.getInbox(number, start, sender);
			}
			
			ArrayList<EmailHeader> headers = inbox.getHeaders();
			JSONObject result = new JSONObject();
			
			JSONArray jArray = new JSONArray();
			for(EmailHeader header : headers) {
				JSONObject json = new JSONObject();
				json.put("sender", header.getSender());
				json.put("subject", header.getSubject());
				json.put("date", header.getDate());
				json.put("index", header.getIndex());
				jArray.put(json);
			}
			
			result.put("headers", jArray);
			result.put("more", inbox.areMore());
			
			response.getWriter().print(result.toString());
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		} catch (CantAccessEmailException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		catch (JSONException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
	}
}
